//
//  HSYAccountInformationViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/6.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYAccountInformationViewController.h"
#import "HSYSubmitSuccessViewController.h"
#import "UIImage+Tools.h"
#import "HSYSetBankcardRequest.h"
#import "HSYQueryBankcardInfoRequest.h"
#import "BQActivityView.h"
#import "HSYCardInformationModel.h"
#import "HSYSelectProvinceViewController.h"
#import "HSYSelectBankBranchViewController.h"
#import "HSYSelectBankViewController.h"
#import "NSString+Validation.h"


@interface HSYAccountInformationViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *cardNOTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *subBranchTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankAccountName;
@property (weak, nonatomic) IBOutlet UITextField *iDnumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankAddressTextField;

@property (nonatomic, strong) NSString *districtCode;
@property (nonatomic, strong) NSString *branchCode;

@property (weak, nonatomic) IBOutlet UIButton *selectBankNameBtn;
@property (weak, nonatomic) IBOutlet UIImageView *selectBankNameRightIcon;

@property (nonatomic, strong) HSYQueryBankcardInfoRequest *matchQuest;

@end

@implementation HSYAccountInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.cardNOTextField.delegate = self;
    self.bankAccountName.delegate = self;
    self.subBranchTextField.delegate = self;
    self.bankAccountName.delegate = self;
    self.iDnumberTextField.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    
    [self.leftAreaLBtn setImage:[UIImage imageNamed:@"left"]  forState:UIControlStateNormal];
    [self.titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.titleButton setTitle:@"填写店铺资料" forState:UIControlStateNormal];
    
    //如果为对公的，提示输入法人身份证号
    if (([HSYUserCenter instatce].appBizShop.isPublic == 1)) {
        self.iDnumberTextField.placeholder = @"法人二代身份证号";
        self.bankNameTextField.placeholder = @"请选择开户行";
//        self.selectBankNameBtn.hidden = YES;
    }else{
        self.selectBankNameRightIcon.hidden = YES;
    }
    
    [self fillbackIfNeed];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)fillbackIfNeed{
    self.cardNOTextField.text = [HSYUserCenter instatce].appBizCard.cardNO;//简称
    self.bankNameTextField.text = [HSYUserCenter instatce].appBizCard.cardBank; //选择地区
    self.subBranchTextField.text = [HSYUserCenter instatce].appBizCard.bankAddress; //街道
    self.bankAccountName.text = [HSYUserCenter instatce].appBizCard.cardAccountName;
    self.iDnumberTextField.text = [HSYUserCenter instatce].appBizCard.idcardNO;
    self.bankAddressTextField.text = [HSYUserCenter instatce].appBizCard.branchDistrictName;
    
    self.districtCode = [HSYUserCenter instatce].appBizCard.branchDistrictCode;
    self.branchCode = [HSYUserCenter instatce].appBizCard.brankCode;
}


-(void)handleGoBackEvent:(UIButton *)sender{
    if (self.navigationController.childViewControllers.count <= 1) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        [super handleGoBackEvent:sender];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)setupNavigationBarBackgroundImage{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor] size:CGSizeMake(1, 1)]  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

//选择开户行
- (void)pushToSelectBankName{
    HSYSelectBankViewController *vc = [[HSYSelectBankViewController alloc] init];
    __weak typeof(self)weakSelf = self;
    vc.selectBankBlock = ^(NSString *branchName, NSString *code){
        weakSelf.bankNameTextField.text = branchName;
    };
    [self.navigationController pushViewController:vc animated:YES];
}


//选择分行
- (void)pushToSelectSubBranch{
    HSYSelectBankBranchViewController *vc = [[HSYSelectBankBranchViewController alloc] init];
    vc.districtCode = self.districtCode;
    vc.bankName = self.bankNameTextField.text;
    __weak typeof(self)weakSelf = self;
    vc.selectBankBranchBlock = ^(NSString *branchName, NSString *code){
        weakSelf.subBranchTextField.text = branchName;
        weakSelf.branchCode = code;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)selectedBank:(UIButton *)sender{
    [self.view endEditing:YES];
    if (([HSYUserCenter instatce].appBizShop.isPublic == 1)){ //对公无法自动匹配开户行，只能选择
        [self pushToSelectBankName];
    }else{
//        [self showMessage:@"自动匹配开户行"];
    }
}

- (IBAction)selectedSubBranch:(UIButton *)sender{
    if (!self.bankNameTextField.text.length && [HSYUserCenter instatce].appBizShop.isPublic == 1) {
        [self showMessage:@"请选择开户行"];
        return;
    }
    
    if ((!self.bankNameTextField.text.length || [self.bankNameTextField.text isEqualToString:@"未识别开户行信息"]) && [HSYUserCenter instatce].appBizShop.isPublic != 1) {
        [self showMessage:@"未识别开户行信息"];
        return;
    }

    
    if (self.districtCode.length == 0) {
        [self showMessage:@"请选择开户地区"];
        return;
    }
    
    [self pushToSelectSubBranch];
}

//选中城市
- (IBAction)selectProvincesBtnClick:(id)sender {
    [self.view endEditing:YES];
    
    HSYSelectProvinceViewController *vc = [[HSYSelectProvinceViewController alloc] init];
    vc.leafCode = 2; //选择到市
    __weak typeof(self)weakSelf = self;
    [vc getProvinceCityCountyinfo:^(NSString *title, NSString *code) {
        weakSelf.bankAddressTextField.text = title;
        weakSelf.districtCode = code;
    }];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)submitBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];

    if (![self checkDataIntegrity]) return;
    
    HSYSetBankcardRequest *task = [[HSYSetBankcardRequest alloc] init];
    task.cardNO = self.cardNOTextField.text;
    task.cardBank = self.bankNameTextField.text;
    task.cardAccountName = self.bankAccountName.text;
    task.sid = [HSYUserCenter instatce].appBizShop.shopID;
    task.bankAddress = self.subBranchTextField.text;
    task.idcardNO = self.iDnumberTextField.text;
    task.branchCode = self.branchCode;
    task.districtCode = self.districtCode;
    
    __weak typeof(self)weakSelf = self;
    [BQActivityView hideActiviTy];

    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        [BQActivityView hideActiviTy];

        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            //保存步骤信息
            [HSYUserCenter instatce].appAuUser.auStep = 4;
            [HSYUserCenter instatce].appBizShop.status = @"2";
            [[HSYUserCenter instatce] saveUserModelToDocuments];
            
            //经过漫长的步骤，终于要提示提交成功了
            [weakSelf summitSuccess];
        }else{
            [weakSelf showMessage:response.resultMessage];
        }
    } failure:^(NSError *error) {
        [BQActivityView hideActiviTy];
        
        if (error.code != NSURLErrorCancelled) {
            [weakSelf showMessage:@"请求超时"];
        }
    }];
}

-(BOOL)checkDataIntegrity{
    if (!self.bankAccountName.text.length) {
        [self showMessage:@"请输入开户名"];
        return NO;
    }else if (![self.bankAccountName.text isValidPersonName]){
        [self showMessage:@"请输入正确联系人名称"];
        return NO;
    }

    
    if (!self.iDnumberTextField.text.length && ([HSYUserCenter instatce].appBizShop.isPublic != 1)) {
        [self showMessage:@"请输入身份证号"];
        return NO;
    }else if (![self.iDnumberTextField.text isValidIdCard]){
        [self showMessage:@"请输入正确身份证号码"];
        return NO;
    }

    if (!self.cardNOTextField.text.length) {
        [self showMessage:@"请输入结算卡卡号"];
        return NO;
    }
    
    if (!self.bankNameTextField.text.length && [HSYUserCenter instatce].appBizShop.isPublic == 1) {
        [self showMessage:@"请选择开户行"];
        return NO;
    }
    
    if ((!self.bankNameTextField.text.length || [self.bankNameTextField.text isEqualToString:@"未识别开户行信息"]) && [HSYUserCenter instatce].appBizShop.isPublic != 1) {
        [self showMessage:@"未识别开户行信息"];
        return NO;
    }
    
    if (!self.subBranchTextField.text.length) {
        [self showMessage:@"请输入支行名称"];
        return NO;
    }
    
    if (!self.districtCode.length) {
        [self showMessage:@"请选择开户地区"];
        return NO;
    }
    
    if (!self.branchCode) {
        [self showMessage:@"联行号不能为空"];
        return NO;
    }
    
    
    return YES;
}

- (void)showNotMatchMessage{
    alert_alam(@"", @"您输入的卡号有误或为暂不支持该银行卡。");
}

- (void)retryMatchBankIfNeed{
    static NSInteger retryTime = 0;
    
    if (retryTime > 3) return; //如果请求失败， 重试3次
    retryTime ++;
    
    [self matchBankNameWithBankCode:self.cardNOTextField.text];
}

- (void)matchBankNameWithBankCode:(NSString *)code{
    self.matchQuest.cardNO = code;
    __weak typeof(self)weakSelf = self;
    [HSYNetworkManager POST:self.matchQuest success:^(HSYResponse *response) {
        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            HSYCardInformationModel *model = [HSYCardInformationModel mj_objectWithKeyValues:response.encryptDataResult];
            if (model.bankName.length > 0) {
                weakSelf.bankNameTextField.text = model.bankName;
                weakSelf.bankNameTextField.textColor = [UIColor blackColor];
            }else{
                weakSelf.bankNameTextField.text = @"未识别开户行信息";
                weakSelf.bankNameTextField.textColor = [UIColor redColor];
                
                [weakSelf performSelector:@selector(showNotMatchMessage) withObject:nil afterDelay:0.5];
//                [weakSelf showNotMatchMessage];
            }
        }
    } failure:^(NSError *error) {
        if (error.code != NSURLErrorCancelled) {
            [weakSelf retryMatchBankIfNeed];
        }
    }];
    
}


#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == self.subBranchTextField || textField == self.bankNameTextField) {
        return NO;
    }
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    //根据银行卡号查询银行卡相关信息 , 对私才有
    if (textField == self.cardNOTextField && textField.text.length > 0 && [HSYUserCenter instatce].appBizShop.isPublic != 1) {
        [textField resignFirstResponder];
        [self matchBankNameWithBankCode:textField.text];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField endEditing:YES];
    return YES;
}

#pragma mark - 信息提交成功 -
- (void)summitSuccess{
    HSYSubmitSuccessViewController *vc = [[HSYSubmitSuccessViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (HSYQueryBankcardInfoRequest *)matchQuest{
    if (!_matchQuest) {
        _matchQuest = [[HSYQueryBankcardInfoRequest alloc] init];
    }
    return _matchQuest;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
